/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import {browserHistory} from 'react-router';
import {Meteor} from 'meteor/meteor';

import React, {Component} from 'react';
import FontIcon from 'material-ui/FontIcon';
import AppBar from 'material-ui/AppBar';
import Popover from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import AutoComplete from 'material-ui/AutoComplete';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation';
import Paper from 'material-ui/Paper';
import SvgIconSettings from 'material-ui/svg-icons/action/settings';
import SvgIconCamera from 'material-ui/svg-icons/image/camera';
import SvgIconImgCollections from 'material-ui/svg-icons/image/collections';
import SvgIconSearch from 'material-ui/svg-icons/action/search';
import SvgIconMenu from 'material-ui/svg-icons/navigation/menu';
import {white} from 'material-ui/styles/colors';
import DatePicker from 'material-ui/DatePicker';

import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

import Tab1 from './Tab1.jsx';
import Tab2Detail from './Tab2Detail.jsx';
import RegisterUsers from './registerUsers';
import RepchainUserRegister from './RepchainUserRegister';


const publicPics = <SvgIconImgCollections/>;
const myPics = <SvgIconCamera/>;
const mySettings = <SvgIconSettings/>;

const styles = {
    toolbar: {
        position: 'fixed',
        top: 0,
        width: '100%',
    },
    footer: {
        position: 'fixed',
        bottom: 0,
        width: '100%',
    },
}

const title_tabs = ['公示图片', '我的图片', '设置', '用户管理', '历史交易'];
const search_themes = ['名称', '作者', '著作权人编号', '登记时间', '图片描述', '哈希值'];

export default class App extends Component {
    constructor(props) {
        super(props);
        let tab = props.params.tab ? props.params.tab : 'tab0';
        let tab_pos = tab.substring(3);
        this.state = {
            selectedIndex: parseInt(tab_pos),
            search_open: 0,
            search_text: '',
            left_menu_open: false,
            search_theme: 0,
            register_user_list_open: false,
            import_cert_open: false,
        };

        this.select = (index) => {
            if (index == 2 && Session.get("curUser")!='none')
                browserHistory.push('/tab2/' + Session.get("curUser").account_address);
            else
                browserHistory.push('/tab' + index);
            this.setState({selectedIndex: index})
        };

    }

    getChildContext() {
        return {muiTheme: getMuiTheme(baseTheme)};
    }

    componentWillMount() {
        if(this.state.selectedIndex > 3){
            this.select(0);
        }else if (Session.get('curUser') === 'none' && this.state.selectedIndex != 0)
            browserHistory.push('/login');
        else if(Session.get('isAdmin')==false){
            this.select(0);
        }
    }

    handleChange(status) {
        const {import_cert_open} = this.state;
        this.setState({import_cert_open: status})
    }

    renderImportUserCert() {
        return <RepchainUserRegister registerUser={true} handleChange={status => this.handleChange(status)}/>
    }

    renderSearch() {
        switch (this.state.selectedIndex) {
            case 0:
            case 1:
                return (
                    <div id='search_group'>
                        <IconButton
                            style={{marginTop: 10, right: -20}}
                            onTouchTap={(e) => {
                                e.preventDefault();
                                if (this.state.search_open) {
                                    this.setState({search_text: ''});
                                }
                                this.setState({search_open: !this.state.search_open});
                            }}
                        >
                            <SvgIconSearch/>
                        </IconButton>
                        {this.state.search_open ?
                            <div id='search_fields'>
                                <SelectField
                                    hintText='主题'
                                    value={this.state.search_theme}
                                    style={{width: 130,}}
                                    onChange={(e, i, v) => this.setState({search_theme: v, search_text: ''})}
                                >
                                    <MenuItem value={0} primaryText={search_themes[0]}/>
                                    <MenuItem value={1} primaryText={search_themes[1]}/>
                                    <MenuItem value={2} primaryText={search_themes[2]}/>
                                    {/*<MenuItem value={3} primaryText={search_themes[3]}/>*/}
                                    <MenuItem value={4} primaryText={search_themes[4]}/>
                                    <MenuItem value={5} primaryText={search_themes[5]}/>
                                </SelectField>
                                {this.state.search_theme != 3 ?
                                    <TextField
                                        hintText='搜索'
                                        style={{width: 130,}}
                                        value={this.state.search_text}
                                        onChange={(e, newVal) => {
                                            this.setState({search_text: newVal});
                                        }}
                                    />
                                    :
                                    <DatePicker
                                        hintText='登记时间'
                                        okLabel='确认'
                                        cancelLabel='取消'
                                        //locale='zh'
                                        textFieldStyle={{width: 130,}}
                                        openToYearSelection={true}
                                        onChange={(e, date) => {
                                            this.setState({search_text: date});
                                        }}
                                    />
                                }
                            </div>
                            :
                            ''
                        }
                    </div>
                );

            case 2:
                return '';
        }
    }

    renderTab() {
        switch (this.state.selectedIndex) {
            case 0:
                return <Tab1 search_theme={this.state.search_theme} search_text={this.state.search_text}/>
            case 1:
                return <Tab1 search_theme={this.state.search_theme} search_text={this.state.search_text}
                             myImages={true}/>
            case 2:
                //如果存在url指定参数,显示该账户
                return <Tab2Detail
                    uid={this.props.params.uid == undefined ? this.props.params.uid : Session.get("curUser").account_address}
                />
            case 3:
                return <RegisterUsers/>
        }
    }

    handleLogOut(e) {
        Meteor.call('account.setCurrentUser', 'none', (err, result) => {
            if (err)
                console.log('Error: logout set cur user none failed, reason: ', err.error);
            else {
                Session.set('curUser', 'none');
                Session.set('isAdmin', false);
                browserHistory.push('/login');
            }
        });
    }


    renderLeftIcon() {
        const {left_menu_open, selectedIndex, import_cert_open} = this.state;
        return (
            <IconMenu
                iconButtonElement={
                    <IconButton
                        onTouchTap={(e) => this.setState({left_menu_open: !left_menu_open})}
                        iconStyle={{color: white}}
                    >
                        <SvgIconMenu/>
                    </IconButton>}
                anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
                targetOrigin={{horizontal: 'left', vertical: 'top'}}
                open={left_menu_open}
                onMouseLeave={()=>{
                    this.setState({left_menu_open:false});
                }}
            >
                {Session.get("isAdmin") && (selectedIndex == 2 || selectedIndex == 3) ?
                    <div>
                        <MenuItem primaryText='用户管理' onTouchTap={(e) => {
                            this.setState({left_menu_open: !left_menu_open});
                            this.select(3);
                        }}/>
                        <MenuItem primaryText='用户注册' onTouchTap={(e) => {
                            this.setState({left_menu_open: !left_menu_open, import_cert_open: true});
                        }}/>
                    </div>
                    :
                    null
                }
                <MenuItem primaryText='关于' onTouchTap={(e) => {
                    this.setState({left_menu_open: false})
                }}/>
                <MenuItem primaryText='退出' onTouchTap={this.handleLogOut}/>
            </IconMenu>
        );
    }

    render() {
        const {import_cert_open} = this.state;
        return (
            <div id="container" className="container">
                <AppBar
                    style={styles.toolbar}
                    title={title_tabs[this.state.selectedIndex]}
                    titleStyle={{overflow: 'visible'}}
                    iconElementLeft={this.renderLeftIcon()}
                >
                    {this.renderSearch()}
                </AppBar>
                {this.renderTab()}
                {import_cert_open ? this.renderImportUserCert() : null}
                <Paper zDepth={3} style={styles.footer}>
                    <BottomNavigation selectedIndex={this.state.selectedIndex}>
                        <BottomNavigationItem
                            label="公示图片"
                            icon={publicPics}
                            onTouchTap={() => this.select(0)}
                        />
                        <BottomNavigationItem
                            label="我的图片"
                            icon={myPics}
                            onTouchTap={() => this.select(1)}
                        />
                        <BottomNavigationItem
                            label="设置"
                            icon={mySettings}
                            onTouchTap={() => this.select(2)}
                        />
                    </BottomNavigation>
                </Paper>
            </div>
        );
    }
}

App.childContextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};